package com.imooc.service.impl;

import com.imooc.config.WeChatAccountConfig;
import com.imooc.dto.OrderDto;
import com.imooc.service.PushMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 功能描述: <br>
 * (推送消息模板Service)
 *
 * @Author:Mr. xyb
 * @Date: 2018/5/18 17:22
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
@Slf4j
public class PushMessageServiceImpl implements PushMessageService {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WeChatAccountConfig wechatAccountConfig;

    @Override
    public void orderStatus(OrderDto orderDto) {
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        // 设置获取的模板id
        wxMpTemplateMessage.setTemplateId(wechatAccountConfig.getTemplateId().get("orderStatus"));
        // 设置获取的用户openid
        wxMpTemplateMessage.setToUser(orderDto.getBuyerOpenid());
        // 编辑需要发送的模板信息
        List<WxMpTemplateData> templateData = Arrays.asList(
                new WxMpTemplateData("first", "亲，记得收货哦"),
                new WxMpTemplateData("keyword1", "微信点餐"),
                new WxMpTemplateData("keyword2", "1888765567"),
                new WxMpTemplateData("keyword3", orderDto.getOrderId()),
                new WxMpTemplateData("keyword4", orderDto.getOrderStatusEnum().getMessage()),
                new WxMpTemplateData("keyword5", "￥" + orderDto.getOrderAmount()),
                new WxMpTemplateData("remark", "欢迎再次光临")
        );
        // 将模板信息设置进消息对象中
        wxMpTemplateMessage.setData(templateData);
        /**
         * 此处一定要try catch，不能抛出异常，如果抛异常会导致完结订单失败
         * 而发送消息的重要程度低于完结订单，不能影响完结订单的业务
         */
        try {
            // 发送消息
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("【微信模板消息】发送失败", e.getError().getErrorMsg());
        }
    }
}
